package com.yanxu.lock.readwrite;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/23-2025
 * @Description: 读写锁
 */
public class CinemaReadWrite {
    static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void main(String[] args) {
        new Thread(() -> {
            read();
        }, "thread1").start();

        new Thread(() -> {
            read();
        }, "thread2").start();

        new Thread(() -> {
            write();
        }, "thread3").start();

        new Thread(() -> {
            write();
        }, "thread4").start();
    }

    public static void read() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到了读锁，正在读取......");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放了读锁......");
            readLock.unlock();
        }
    }

    public static void write() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到了写锁，正在写入......");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放了写锁......");
            writeLock.unlock();
        }
    }
}